#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QInputDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->addTaskButton, &QPushButton::clicked, this, &MainWindow::addTask);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addTask()
{
    bool ok;
    QString name = QInputDialog::getText(this,
                                         tr("Add task"),
                                         tr("Task name"),
                                         QLineEdit::Normal,
                                         tr("Untitled task"),
                                         &ok);
    if(ok && !name.isEmpty())
    {
        qDebug() << "Adding new task";
        Task* task = new Task(name);
        m_tasks.append(task);
        ui->tasksLayout->addWidget(task);

        connect(task, &Task::removed, this, &MainWindow::removeTask);
        connect(task, &Task::statusChanged, this, &MainWindow::statusChanged);

        updateStatus();
    }
}

void MainWindow::removeTask(Task *task)
{
    m_tasks.removeOne(task);
    ui->tasksLayout->removeWidget(task);
    task->setParent(nullptr);
    delete task;

    updateStatus();
}

void MainWindow::statusChanged(Task * /*task*/)
{
    updateStatus();
}

void MainWindow::updateStatus()
{
    int completed_count = 0;
    for( auto task : m_tasks )
    {
        if(task->isCompleted())
        {
            ++completed_count;
        }
    }
    int todo_count = m_tasks.size()-completed_count;

    ui->statusLabel->setText(
                QString("Status: %1 todo / %2 completed")
                .arg(todo_count)
                .arg(completed_count));
}
